package com.hgm.flopgame2.activity

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ValueAnimator
import android.content.Intent
import android.os.Bundle
import android.os.SystemClock
import android.view.View
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.room.Room
import com.hgm.flopgame2.adapter.CardAdapter
import com.hgm.flopgame2.database.Score
import com.hgm.flopgame2.database.ScoreDataBase
import com.hgm.flopgame2.databinding.ActivityMainBinding
import java.io.Serializable


class MainActivity : AppCompatActivity() {

    private val binding: ActivityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    //记录他们的类型
    private var t1 = 0
    private var t2 = 0
    //记录他们的下标
    private var p1 = 0
    private var p2 = 0
    //记录他们的成功次数
    private var count = 0
    private var name = "Test"
    private var time: Long = 0
    private lateinit var db: ScoreDataBase
    private var itemViewHolder: CardAdapter.MyViewHolder? = null
    //重新游戏
    private var tag = 0
    private var up_name: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //隐藏状态栏
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        setContentView(binding.root)

        initData()
        initView()
    }




    private fun initData() {
        //1.获取登录的用户名
        name = intent.getStringExtra("name").toString()


        //2.获取重新游戏的用户名
        tag = intent.getIntExtra("tag", 0)
        up_name = intent.getStringExtra("up_name").toString()
    }


    private fun initView() {
        //禁止滑动-布局管理器
        var gridLayoutManager = object : GridLayoutManager(this, 4, RecyclerView.VERTICAL, false) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }


        //往集合里添加16个元素，并随机打乱
        var cardList = arrayListOf<Int>()
        for (i in 1..2) {
            for (j in 1..8) {
                cardList.add(j)
            }
        }
        cardList.shuffle()


        //初始化Recyclerview
        var cardAdapter = CardAdapter(cardList)
        binding.recyclerView.apply {
            adapter = cardAdapter
            layoutManager = gridLayoutManager
        }


        //开始游戏：计时
        binding.chronometer.start()
        cardAdapter.setOnItemClickListener(object : CardAdapter.OnItemClickListener {
            override fun onItemClick(
                holder: CardAdapter.MyViewHolder,
                type: Int,
                position: Int,
                rootView: View,
                view1: View,
                view2: View
            ) {
                start3DRotateAnimator(holder.rootView, holder.card1, holder.card2)
                android.os.Handler().postDelayed({
                    //第一次点击
                    if (t1 == 0) {
                        t1 = type
                        p1 = position
                        itemViewHolder = holder
                    } else {
                        t2 = type
                        p2 = position
                        //成功
                        if (t1 == t2 && p1 != p2) {
                            //消除卡片
                            itemViewHolder!!.rootView.visibility = View.GONE
                            holder.rootView.visibility = View.GONE
                            count++

                            //全部消完
                            isComplete()

                        } else {//失败
                            start3DRotateAnimator(
                                itemViewHolder!!.rootView,
                                itemViewHolder!!.card2,
                                itemViewHolder!!.card1
                            )
                            start3DRotateAnimator(holder.rootView, holder.card2, holder.card1)
                        }
                    }
                }, 600)
                //失败之后要重置
                if (t2 != 0) {
                    t1 = 0
                    t2 = 0
                    p1 = 0
                    p2 = 0
                    itemViewHolder = null
                }
            }
        })
    }


    /**
     * 动画
     */
    private fun start3DRotateAnimator(rootView: View, view1: View, view2: View) {
        val from: Float = if (view1.visibility === View.INVISIBLE) 0F else 180.toFloat()
        val to: Float = if (from == 0f) 180F else 0.toFloat()
        val rotateAnimator = ValueAnimator.ofFloat(from, to)
        rotateAnimator.addUpdateListener { valueAnimator ->
            val value = valueAnimator.animatedValue as Float
            if (value <= 90) {
                if (view1.visibility !== View.INVISIBLE) {
                    view1.visibility = View.INVISIBLE
                    view2.visibility = View.VISIBLE
                }
                rootView.rotationY = value
            } else {
                if (view1.visibility !== View.VISIBLE) {
                    view1.visibility = View.VISIBLE
                    view2.visibility = View.INVISIBLE
                }
                rootView.rotationY = value - 180
            }
        }
        val tzAnimator = ValueAnimator.ofFloat(1f, 0.6f, 1f)
        tzAnimator.addUpdateListener { valueAnimator ->
            val value = valueAnimator.animatedValue as Float
            rootView.scaleX = value
            rootView.scaleY = value
        }
        val set = AnimatorSet()
        set.duration = 600
        set.playTogether(rotateAnimator, tzAnimator)
        set.addListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {
                // 开启硬件加速
                rootView.setLayerType(View.LAYER_TYPE_HARDWARE, null)

                // 这里做页面翻转前的操作
            }

            override fun onAnimationEnd(animation: Animator) {
                // 关闭硬件加速
                rootView.setLayerType(View.LAYER_TYPE_NONE, null)

                // 这里做页面翻转后的操作

            }

            override fun onAnimationCancel(animator: Animator) {}
            override fun onAnimationRepeat(animator: Animator) {}
        })
        set.start()
    }


    /**
     * 完成逻辑
     */
    private fun isComplete() {
        //游戏完成
        if (count == 8) {
            //获取时间
            binding.chronometer.stop()
            time = SystemClock.elapsedRealtime() - binding.chronometer.base

            //创建和获取数据库
            db = Room.databaseBuilder(
                this@MainActivity,
                ScoreDataBase::class.java,
                "Score.db"
            )
                .allowMainThreadQueries()
                .build()


            //定义参数记录APP是几次启动！！！
            val shp = getSharedPreferences("data", MODE_PRIVATE)
            val isFirst = shp.getBoolean("isFirst",true)//默认值第一次



            if (tag == 1) {//TODO:用户重新游戏
                db.getScoreDao().updateScore(time / 1000, up_name)
                name = up_name
            } else {//TODO：用户首次游戏
                if (isFirst) {
                    //app第一次启动，加载数据
                    shp.edit().putBoolean("isFirst", false).apply()
                    val s1 = Score(null, "Player1", 30)
                    val s2 = Score(null, "Player2", 51)
                    val s3 = Score(null, "Player3", 143)
                    db.getScoreDao().apply {
                        insertScore(s1)
                        insertScore(s2)
                        insertScore(s3)
                    }
                }
                //app不是第一次启动
                var score = Score(null, name, time / 1000)
                db.getScoreDao().insertScore(score)
            }


            //获取所有数据集合
            var allScore = db.getScoreDao().getAllScore()


            //传递成绩到排行榜
            var intent = Intent(this@MainActivity, ScoreActivity::class.java)
            intent.putExtra("list", allScore as Serializable)
            intent.putExtra("name", name)
            startActivity(intent)
            finish()
        }
    }


}